--[[
NetFlow - OpenWRT 网络流量管理系统
Web界面控制器

本文件实现了基于LuCI的Web界面控制器，
提供用户友好的图形界面配置和监控功能。
]]--

-- 引入LuCI模块（使用pcall防止模块加载失败导致整个控制器崩溃）
local function safe_require(module_name)
    local success, module = pcall(require, module_name)
    if success then
        return module
    else
        return {}
    end
end

local http = safe_require("luci.http")
local sys = safe_require("luci.sys")

local json
local success_jsonc, jsonc = pcall(require, "luci.jsonc")
local success_json, json_lib = pcall(require, "luci.json")
if success_jsonc then
    json = jsonc
elseif success_json then
    json = json_lib
else
    -- 提供一个基本的JSON解析实现，避免无法使用的情况
    json = {
        parse = function(str)
            if not str or str == "" then return {} end
            -- 简单情况下返回空对象
            return {}
        end
    }
end

local uci
local success_uci, uci_lib = pcall(require, "luci.model.uci")
if success_uci then
    if type(uci_lib.cursor) == "function" then
        uci = uci_lib.cursor()
    else
        uci = {}
    end
else
    uci = {}
end



local http = require "luci.http"
local sys = require "luci.sys"
local json = require "luci.jsonc"
local uci = require "luci.model.uci"
local cursor = uci.cursor()

-- 定义模块
module("luci.controller.netflow", package.seeall)

-- 索引函数（LuCI入口点）
function index()
    -- 注册主页面到网络菜单下
    entry({"admin", "network", "netflow"}, 
          alias("admin", "network", "netflow", "overview"), 
          _("NetFlow 流量管理"), 60)
    
    -- 注册子页面
    entry({"admin", "network", "netflow", "overview"}, 
          template("netflow/overview"), 
          _("系统概览"), 10)
    
    entry({"admin", "network", "netflow", "classification"}, 
          cbi("netflow/classification"), 
          _("流量分类"), 20)
    
    entry({"admin", "network", "netflow", "priority"}, 
          cbi("netflow/priority"), 
          _("优先级设置"), 30)
    
    entry({"admin", "network", "netflow", "bandwidth"}, 
          cbi("netflow/bandwidth"), 
          _("带宽管理"), 40)
    
    entry({"admin", "network", "netflow", "statistics"}, 
          template("netflow/statistics"), 
          _("统计信息"), 50)
    
    entry({"admin", "network", "netflow", "settings"}, 
          cbi("netflow/settings"), 
          _("系统设置"), 60)
    
    -- 注册AJAX接口
    entry({"admin", "network", "netflow", "status"}, 
          call("action_status"), 
          nil)
    
    entry({"admin", "network", "netflow", "metrics"}, 
          call("action_metrics"), 
          nil)
    
    entry({"admin", "network", "netflow", "flow_stats"}, 
          call("action_flow_stats"), 
          nil)
    
    entry({"admin", "network", "netflow", "app_stats"}, 
          call("action_app_stats"), 
          nil)
end

-- 获取系统状态
function action_status()
    local status = {}
    
    -- 检查系统服务是否运行
    status.running = (sys.call("pidof netflow >/dev/null") == 0)
    
    -- 获取系统版本
    status.version = "1.0"
    
    -- 获取系统运行时间
    local uptime_file = io.open("/var/run/netflow/uptime", "r")
    if uptime_file then
        status.uptime = uptime_file:read("*l")
        uptime_file:close()
    else
        status.uptime = "未知"
    end
    
    -- 返回JSON格式数据
    http.prepare_content("application/json")
    http.write_json(status)
end

-- 获取网络指标
function action_metrics()
    local metrics = {}
    
    -- 从统计文件读取网络指标
    local stats_file = io.open("/var/run/netflow/metrics.json", "r")
    if stats_file then
        local content = stats_file:read("*all")
        metrics = json.parse(content) or {}
        stats_file:close()
    end
    
    -- 如果文件不存在或解析失败，使用默认值
    if not metrics.load_factor then
        metrics = {
            load_factor = 0,
            congestion_index = 0,
            traffic = {
                current_bps = 0,
                capacity_bps = 100000000
            }
        }
    end
    
    -- 返回JSON格式数据
    http.prepare_content("application/json")
    http.write_json(metrics)
end

-- 获取流量统计
function action_flow_stats()
    local stats = {}
    
    -- 从统计文件读取流量统计
    local stats_file = io.open("/var/run/netflow/flow_stats.json", "r")
    if stats_file then
        local content = stats_file:read("*all")
        stats = json.parse(content) or {}
        stats_file:close()
    end
    
    -- 返回JSON格式数据
    http.prepare_content("application/json")
    http.write_json(stats)
end

-- 获取应用统计
function action_app_stats()
    local stats = {}
    
    -- 从统计文件读取应用统计
    local stats_file = io.open("/var/run/netflow/app_stats.json", "r")
    if stats_file then
        local content = stats_file:read("*all")
        stats = json.parse(content) or {}
        stats_file:close()
    end
    
    -- 返回JSON格式数据
    http.prepare_content("application/json")
    http.write_json(stats)
end
